<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1224" @ok="handleSubmit">
    <a-tabs defaultActiveKey="1" size="small">
      <a-tab-pane tab="基本内容" key="1">
        <BasicForm :disabled="isDetail" @register="registerForm" ref="formRef">
          <template #billTypeSlot="{ model, field }">
            <a-input-search v-model:value="model[field]" placeholder="请选择单据类型" :disabled="isDetail" readonly @search="billTypeOpen" />
          </template>
          <template #materialSlot="{ model, field }">
            <a-input-search @search="handleView(null)" placeholder="请选择产品" :disabled="isDetail" readonly v-model:value="model[field]" />
          </template>
          <template #completeWarehouseSlot="{ model, field }">
            <a-input-search v-model:value="model[field]" placeholder="请选择完工储存地点" :disabled="isDetail" readonly @search="warehouseOpen(2)" />
          </template>
          <template #billStatusSlot="{ model, field }">
            <a-select :disabled="isDetail || flag" v-model:value="model[field]" placeholder="请选择工单状态"
              ><a-select-option :value="0">开立</a-select-option>
              <a-select-option :value="1">已核准</a-select-option>
              <a-select-option :value="2">已开工</a-select-option>
              <a-select-option :value="3">已完工</a-select-option>
            </a-select>
          </template>
        </BasicForm>
        <!-- { value: 0, label: '开立' }, { value: 1, label: '核准中' }, { value: 2, label: '已核准' }, { value: 3, label: '开工' }, { value: 4, label: '完工' } -->
      </a-tab-pane>
      <a-tab-pane tab="存储信息" key="2">
        <BasicForm :disabled="isDetail" @register="registerStorageForm" ref="formRef">
          <template #storageWarehouseSlot="{ model, field }">
            <a-input-search v-model:value="model[field]" placeholder="请选择入库储存地点" :disabled="isDetail" readonly @search="warehouseOpen(1)" />
          </template>
        </BasicForm>
      </a-tab-pane>
    </a-tabs>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="备料信息" key="busProductionPlanInformation" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busProductionPlanInformation"
          :rowNum="true"
          rowNumKey="rowNum"
          :loading="busProductionPlanInformationTable.loading"
          :columns="busProductionPlanInformationTable.columns"
          :dataSource="busProductionPlanInformationTable.dataSource"
          :height="340"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #action="props">
            <a-input-search
              @search="handleView(props)"
              placeholder="请选择产品"
              :disabled="isDetail"
              readonly
              v-model:value="props.row.materialCode"
            ></a-input-search>
          </template>

          <template #warehouse="props">
            <a-input-search
              @search="handleWarehouseView(props)"
              placeholder="请选择仓库"
              :disabled="isDetail"
              readonly
              v-model:value="props.row.storageLocation"
            ></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"> </billTypeSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"> </materialSelectModel>
  <!-- 仓库 -->
  <warehouseSelectModel @register="warehouseRegModal" @getSelectResult="warehousehandleSuccess" v-bind="getBindValue"> </warehouseSelectModel>
  <!-- 入库储存地点和完工储存地点 -->
  <storageAndCompleteWarehouseSelectModel
    @register="storageAndCompleteWarehouseRegModal"
    @getSelectResult="storageAndCompleteWarehousehandleSuccess"
    v-bind="getBindValue"
  />
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, formStoreSchema, busProductionPlanInformationColumns, busProductionPlanProcessTableColumns } from '../BusProductionPlan.data';
import { saveOrUpdate, busProductionPlanInformationList, busProductionPlanProcessTableList,getBomListByMaterialId } from '../BusProductionPlan.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import materialSelectModel from '/@/views/components/materialSelectModel.vue';
import warehouseSelectModel from '/@/views/components/warehouseSelectModel.vue';
import { localStorage } from '/@/utils/store/locaStore';
import storageAndCompleteWarehouseSelectModel from '/@/views/components/warehouseSelectModel.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
const refKeys = ref(['busProductionPlanInformation']);
const activeKey = ref('busProductionPlanInformation');
const busProductionPlanInformation = ref();
const tableRefs = { busProductionPlanInformation };
const busProductionPlanInformationTable = reactive({
  loading: false,
  dataSource: [],
  columns: busProductionPlanInformationColumns,
});

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue: setFieldsFormsValue, getFieldsValue: getFieldsValueForm, validate }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 6 },
});
const [registerStorageForm, { setFieldsValue: setFieldsStoreValue, getFieldsValue: getFieldsValueStoreForm }] = useForm({
  labelWidth: 120,
  schemas: formStoreSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 6 },
});
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [warehouseRegModal, { openModal: openWarehouseModal }] = useModal();
const [storageAndCompleteWarehouseRegModal, { openModal: openStorageAndCompleteWarehouseModal }] = useModal();

const flag = ref<boolean>(true)
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  flag.value = data.record.billStatus !== 0 && data.record.billStatus !== 1
  
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsFormsValue({
      ...data.record,
    });
    requestSubTableData(busProductionPlanInformationList, { id: data?.record?.id }, busProductionPlanInformationTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});

//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

let index: number | null = null;
//打开选择料品
function handleView(props) {
  if (props) index = props.params.$rowIndex;
  else index = null;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开仓库
function handleWarehouseView(props) {
  index = props.params.$rowIndex;
  openWarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//仓库回写
function warehousehandleSuccess(val, values) {
  busProductionPlanInformationTable.dataSource = busProductionPlanInformation.value!.getTableData();
  busProductionPlanInformationTable.dataSource[index].issueWarehouseName = val[0].label;
  busProductionPlanInformationTable.dataSource[index].issueWarehouseId = val[0].value;
}

// 区分完工储存地点和入库储存地点
let warehouseNum: number | null = null;
// 储存地点选择
function warehouseOpen(num) {
  warehouseNum = num;
  openStorageAndCompleteWarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
// 储存地点回写
function storageAndCompleteWarehousehandleSuccess(val) {
  // 入库储存地点
  if (warehouseNum == 1) {
    setFieldsStoreValue({
      storageWarehouseId: val[0].value,
      storageWarehouseName: val[0].label,
    });
  }
  // 完工储存地点
  if (warehouseNum == 2) {
    setFieldsFormsValue({
      completeWarehouseId: val[0].value,
      completeWarehouseName: val[0].label,
    });
  }
}
//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busProductionPlanInformation';
  busProductionPlanInformationTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busProductionPlanInformationList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单

    // 获取基础信息表单数据
    const formValues = getFieldsValueForm();
    if (localStorage.get('sourceOrganizationId')) {
      formValues.sourceOrganizationName = localStorage.get('sourceOrganizationId');
      localStorage.remove('sourceOrganizationId');
    }
    if (localStorage.get('ownerOrganizationId')) {
      formValues.ownerOrganizationName = localStorage.get('ownerOrganizationId');
      localStorage.remove('ownerOrganizationId');
    }
    if (localStorage.get('productDepartmentId')) {
      formValues.productDepartmentName = localStorage.get('productDepartmentId');
      formValues.productDepartmentCode = localStorage.get('productDepartmentIdCode');
      localStorage.remove('productDepartmentId');
      localStorage.remove('productDepartmentIdCode');
    }
    // 获取存储信息表单数据
    let storeFormData = getFieldsValueStoreForm();
    const data = Object.assign(formValues, storeFormData);
    busProductionPlanInformationTable.dataSource = busProductionPlanInformation.value!.getTableData();
    
    data.busProductOrderMaterialList = busProductionPlanInformationTable.dataSource;
    
    await saveOrUpdate(data, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const getBindValue = Object.assign({}, '');
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
    tableName: 'bus_product_order',
  });
}
//单据类型回写
function billTypehandleSuccess(val) {
  setFieldsFormsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//料品回写
function materialhandleSuccess(val, values) {
  // index有值  代表是子表  否则是主表
  if (index === 0 || index) {
    busProductionPlanInformationTable.dataSource = busProductionPlanInformation.value!.getTableData();
    busProductionPlanInformationTable.dataSource[index].materialName = val[0].label;
    busProductionPlanInformationTable.dataSource[index].materialId = val[0].value;
    busProductionPlanInformationTable.dataSource[index].materialCode = val[0].item.code;
    busProductionPlanInformationTable.dataSource[index].specifications = val[0].item.spec;
    // 自动带出单位
    busProductionPlanInformationTable.dataSource[index].unitId = val[0].item.stockUnitId;
    busProductionPlanInformationTable.dataSource[index].unitName = val[0].item.stockUnitName;
  } else {
    getBomByMaterialId(val[0].value);
    setFieldsFormsValue({
      materialId: val[0].value,
      materialName: val[0].label,
      materialCode: val[0].item.code,
      specifications: val[0].item.spec,
      unitId: val[0].item.stockUnitId,
      unitName: val[0].item.stockUnitName,
    });
  }
}
// 根据料品id  获取产品BOM信息  赋值完工储存地点及生产部门
function getBomByMaterialId(id) {
  let params = {
    materialId : id
  };
  getBomListByMaterialId(params).then(res => {
    if(res.records.length > 0) {
      // 取第一个的值
      let obj = res.records[0];
      setFieldsFormsValue({
        completeWarehouseId: obj.warehouseId,
        completeWarehouseName: obj.warehouseName,
        productDepartmentId: obj.productDepartmentId,
        productDepartmentName: obj.productDepartmentName,
        productDepartmentCode: obj.productDepartmentCode
      });
      
    }
  })
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>